var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors')
var jwt = require('jsonwebtoken')
var secret = 'asdfasdfasdfas46546asdfasdf654a6sdfa' //私钥

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
const { createProxyMiddleware } = require('http-proxy-middleware');


var app = express();
require('./database/connect.js') //引入数据库连接文件
app.use(cors({
    origin:'http://localhost:8081'
}))  //处理后端接口跨域问题
app.use('/hehe', createProxyMiddleware({  //服务代理
    target:'https://shopapi.smartisan.com', //代理的目标服务器地址
    pathRewrite:{ //路径重写
        '^/hehe':''  //剔除代理路径
    },
    changeOrigin: true 
}));
app.use('/node', createProxyMiddleware({  //服务代理
    target:'http://localhost:3000', //代理的目标服务器地址
    pathRewrite:{ //路径重写
        '^/node':''  //剔除代理路径
    },
    changeOrigin: true 
}));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/stu',(req,res,next)=>{
    // console.log('接口路由拦截',req.headers);
    let {token} = req.headers
    jwt.verify(token,secret,(err,decoded)=>{ //err时token鉴权失败时的信息，decoded是鉴权成功后获取的token签发信息
        console.log(err,decoded);
        if(err){  //token合法性
            res.send({
                code:103,
                msg:'非法token，请登录'
            })
            return
        }
        let {time,expire} = decoded  //提取token携带的签发时间、有效时长
        let now = Date.now()  //鉴权的当前时间
        if(now-time>=expire){  //token有效性
            res.send({
                code:103,
                msg:'token过期，请重新登录'
            })
            return
        }
        next() //放行
    })
    
} ,indexRouter);

app.use('/users', usersRouter);
app.use('/local', require('./routes/local.js'));

//在云服务器中编辑的代码
module.exports = app;
